package com.siecom.module;

import android.graphics.Bitmap;
import android.util.Log;

import com.ivsign.android.IDCReader.IDCReadInterface;
import com.siecom.bean.IdentityInfoBean;
import com.siecom.constconfig.ConstDefine;
import com.siecom.hostservice.MainActivity;
import com.siecom.nativelibs.rkGpioControlNative;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.tool.WltLib;
import com.siecom.zhq.hostservice.R;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zhq on 2016/6/23.
 */
public class IDCardModule extends SerialPortModule {

    public static final String TAG = "IDCardModule";
    private String serialDev;
    private int baudRate = 115200;

    private static IDCardModule ourInstance = new IDCardModule();

    //发送信息
    private final String sCmdReadSAMID = "AAAAAA9669000312FFEE";
    private final String sCmdFindCard = "AAAAAA96690003200122";
    private final String sCmdSelectCard = "AAAAAA96690003200221";
    private final String sCmdReadCardBase = "AAAAAA96690003300132";
    private final String sCmdReadNewAddress = "AAAAAA96690003300330";
    private final String sCmdReadCardFinger = "AAAAAA96690003301023";
    //命令返回信息
    private final String sFIND_NO_CARD = "AAAAAA9669000400008084";
    private final String sFIND_SUCC = "AAAAAA9669000800009F0000000097";
    private final String sREAD_NO_CARD = "AAAAAA9669000400004145";
    private final String sSELECT_NO_CARD = "AAAAAA9669000400008185";
    private final String sSELECT_SUCC = "AAAAAA9669000C00009000000000000000009C";

    public static IDCardModule getInstance() {
        return ourInstance;
    }

    protected boolean isOpen = false;

    private IDCardModule() {
        super();

    }

    public boolean init() {
        this.serialDev = ConstDefine.getIdModulePort();
        if (this.serialDev == null) {
            isOpen = false;
            return false;
        }
        if (initSerialPort(this.serialDev, this.baudRate)) {
            Log.e("initserial", "open id");
            isOpen = true;
            return true;
        }
        return false;
    }

    public boolean isOpen() {

        return isOpen;
    }

    public IdentityInfoBean ReadBaseCardInfo(String[] sRet) {
        if (!isOpen)
            return null;
        byte[] mBuffer = new byte[2320];
        int[] length = new int[1];
//        if (this.ReadCardBase(mBuffer, length)) {
        return decodeInfo(mBuffer, false, false);
//        }
//        return null;
    }

    public IdentityInfoBean ReadAllCardInfo(String[] sRet) {
//        if (!isOpen) return null;
        String sNewAddress = "";
        byte[] mBuffer = new byte[2320];
        int[] length = new int[1];
//        if (ReadCardNewAddress(mBuffer, length)) {
//            try {
//                sNewAddress = new String(mBuffer, 3, 70, "UTF-16LE").trim();
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }
//        if (this.ReadCardFinger(mBuffer, length)) {
//            Log.e("ReadCardFinger","---");
//            if (info != null) {
//                info.setNewAddress(sNewAddress);
//            }
//            return info;
//        }

        return decodeInfo(mBuffer, true, true);
    }


    public boolean FindCard(String[] sRet) {
        byte[] mBuffer = new byte[2320];
        int[] length = new int[1];
        boolean bRet = SendAndRecv(sCmdFindCard, mBuffer, length, 2000);
        if (!bRet) return false;
        sRet[0] = ByteTool.byte2hex(mBuffer, 0, length[0], false);
        if (sRet[0].equalsIgnoreCase(sFIND_SUCC)) return true;
        return false;
    }

    public boolean SelectCard(String[] sRet) {
        byte[] mBuffer = new byte[2320];
        int[] length = new int[1];
        boolean bRet = SendAndRecv(sCmdSelectCard, mBuffer, length, 1000);
        if (!bRet) return false;
        sRet[0] = ByteTool.byte2hex(mBuffer, 0, length[0], false);
        if (sRet[0].equalsIgnoreCase(sSELECT_SUCC)) return true;
        return false;
    }

    private boolean ReadCardBase(byte[] mBuffer, int[] length) {
        boolean bRet = SendAndRecv(sCmdReadCardBase, mBuffer, length, 5000);
        if (!bRet) return false;
        if (mBuffer[0] == (byte) 0x00 && mBuffer[1] == (byte) 0x00 && mBuffer[2] == (byte) 0x90)
            return true;
        return false;
    }

    private boolean ReadCardFinger(byte[] mBuffer, int[] length) {
        boolean bRet = SendAndRecv(sCmdReadCardFinger, mBuffer, length, 20000);
        if (!bRet) return false;
        if (mBuffer[0] == (byte) 0x00 && mBuffer[1] == (byte) 0x00 && mBuffer[2] == (byte) 0x90)
            return true;
        return false;
    }

    private boolean ReadCardNewAddress(byte[] mBuffer, int[] length) {
        boolean bRet = SendAndRecv(sCmdReadNewAddress, mBuffer, length, 1500);
        if (!bRet) return false;
        if (mBuffer[0] == (byte) 0x00 && mBuffer[1] == (byte) 0x00 && mBuffer[2] == (byte) 0x90)
            return true;
        return false;
    }
    byte[] data;
    private IdentityInfoBean decodeInfo(byte[] buffer, boolean haveFinger, boolean decodePhoto) {

        WltLib.checkLibFile();
        IdentityInfoBean people = new IdentityInfoBean();
        try {
            {
                // TODO Auto-generated method stub
                Bitmap[] bmp = new Bitmap[1];
                data = IDCReadInterface.DLL_IDReadCard(bmp);
                LogUtil.e(TAG,"IDCReadInterface.DLL_IDReadCard" );
                for (int i = 0; i < 2; i++) {
                    if(data == null){
                        data = IDCReadInterface.DLL_IDReadCard(bmp);
                        LogUtil.e(TAG,"IDCReadInterface.DLL_IDReadCard " + i  );
                    }
                }
                if(data!=null){
                    people.setIcon(bmp[0]);
                }
//                for(int i = 0; i < 24; i++){
//                    if(data != null){
//                        break;
//                    }else{
//                        IDCReadInterface.DLL_IDOpen();
//                        data = IDCReadInterface.DLL_IDReadCard(bmp);
//                    }
//                    IDCReadInterface.DLL_IDClose();
//
//                }
                if(data == null){
                    LogUtil.e("GJ","未检测到卡片");
//                    Toast.makeText(this, "未检测到卡片", Toast.LENGTH_SHORT).show();
                    return null ;
                }

                LogUtil.e(TAG,"原始数据==" + ByteTool.byte2hex(data));

                try {
                    byte[] dataBuf = new byte[256];

                    for(int i = 0; i < 256; i++)
                    {
                        dataBuf[i] = data[6 + i];
                    }
                    byte[] head = new byte[1024];
                    System.arraycopy(data,6 + 256,head,0,1024);
                    String headStr = ByteTool.byte2hex(head);
                    LogUtil.e(TAG,"头像数据：" + headStr);
                    people.setImageStr(headStr);

                    byte[] finger = null;
                    if(data.length >= (6 + 256 + 1024 + 1024)){
                        finger = new byte[1024];
                        System.arraycopy(data,6+256+1024,finger,0,1024);
                    }

                    String TmpStr = new String(dataBuf, StandardCharsets.UTF_16LE);
                    LogUtil.e(TAG,"TmpStr--" + TmpStr);

//                    TmpStr = new String(TmpStr.getBytes("UTF-8"));
//                    LogUtil.e(TAG,"-----" + TmpStr);
                    String[] decodeInfo = new String[12];
                    String cardType = TmpStr.substring(124, 125);
                    LogUtil.e(TAG,"cardType==" + cardType);
                    if(cardType.equals("I")) {

                        String enName = new String(dataBuf, 0, 120, "UTF-16LE").trim();
                        Log.e("enName",enName);

                        String fprSex = new String(dataBuf, 120, 2, "UTF-16LE").trim();
                        String frpIDNo = new String(dataBuf, 122, 30, "UTF-16LE").trim();
                        Log.e("frpIDNo",frpIDNo);

                        String countryCode = new String(dataBuf, 152, 6, "UTF-16LE").trim();
                        Log.e("countryCode",countryCode);

                        String CHNName = new String(dataBuf, 158, 30, "UTF-16LE").trim();
                        Log.e("CHNName",CHNName);

                        String validStart = new String(dataBuf, 188, 16, "UTF-16LE").trim();
                        Log.e("validStart",validStart);

                        String validEnd = new String(dataBuf, 204, 16, "UTF-16LE").trim();
                        Log.e("validEnd",validEnd);

                        String Birthday = new String(dataBuf, 220, 16, "UTF-16LE").trim();
                        Log.e("Birthday",Birthday);

                        String idVer = new String(dataBuf, 236, 4, "UTF-16LE").trim();
                        Log.e("idVer",idVer);

                        String issuingAuthorityCode = new String(dataBuf, 240, 8, "UTF-16LE").trim();
                        Log.e("issuingAuthorityCode",issuingAuthorityCode);

                        people.fullName = CHNName;
                        people.birthday = Birthday;
                        people.idNo = frpIDNo;
                        people.idOrg = issuingAuthorityCode;
                        people.beginDate = validStart;
                        people.endDate = validEnd;
                        //  bean.idAddr = m_strAddress;
                        people.countryCode= countryCode;
                        people.nation = countryMap.get(countryCode);
                        if (fprSex.equals("1")){
                            people.sex  = "男";
                        } else{
                            people.sex  = "女";
                        }
                        people.cardType = "I";
                        people.cardVer = idVer;
                        people.enName = enName;

//                        decodeInfo[0] = TmpStr.substring(0, 60)+TmpStr.substring(79, 94); //name
//                        decodeInfo[1] = TmpStr.substring(60, 61);// gender(1)
//                        decodeInfo[2] = TmpStr.substring(76, 79); // nation (2)
//                        decodeInfo[3] = TmpStr.substring(110, 118); // birthday (8)
//                        decodeInfo[4] = ""; // address
//                        decodeInfo[5] = TmpStr.substring(61, 76); //id (18)
//                        decodeInfo[6] = TmpStr.substring(120, 124); //depart (15)
//                        decodeInfo[7] = TmpStr.substring(94, 102); // tsYYMMDD
//                        decodeInfo[8] = TmpStr.substring(102, 110); //tpYYMMDD
//
//                        decodeInfo[10] = TmpStr.substring(118, 120);
//                        decodeInfo[11] = TmpStr.substring(124, 125);
//
//
//                        if (decodeInfo[1].equals("1"))
//                            decodeInfo[1] = "男";
//                        else
//                            decodeInfo[1] = "女";
//                        people.setSex(decodeInfo[1]);
//
//                        people.setIdNo(decodeInfo[5]);
//
//                        people.setCountryCode(decodeInfo[6]);
//
//                        Log.e("countryCode", decodeInfo[6]);
//
//                        String CHNName = new String(dataBuf, 158, 30, "UTF-16LE").trim();
//
//                        Log.e("CHNName", CHNName);
//
//                        people.setFullName(CHNName);
//
//                        String validStart = new String(dataBuf, 188, 16, "UTF-16LE").trim();
//
//                        Log.e("validStart", validStart);
//
//                        people.setBeginDate(validStart);
//
//                        String validEnd = new String(dataBuf, 204, 16, "UTF-16LE").trim();
//
//                        Log.e("validEnd", validEnd);
//
//                        people.setEndDate(validEnd);
//
//                        String Birthday = new String(dataBuf, 220, 16, "UTF-16LE").trim();
//
//                        Log.e("Birthday", Birthday);
//
//                        people.setBirthday(Birthday);
//
//                        String idVer = new String(dataBuf, 236, 4, "UTF-16LE").trim();
//
//                        Log.e("idVer", idVer);
//
//                        people.setCardVer(idVer);
//
//                        String issuingAuthorityCode = new String(dataBuf, 240, 8, "UTF-16LE").trim();
//
//                        Log.e("issuingAuthorityCode", issuingAuthorityCode);
//
//                        people.setIdOrg(issuingAuthorityCode);
//
//                        people.setCardType("I");
//
//                        people.setNation(countryMap.get(decodeInfo[6]));

                    }else if (cardType.equals("J")){
                        String GAT_Name = (new String(dataBuf, 0, 30, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_NAME="+GAT_Name);
                        String GAT_SexCode = (new String(dataBuf, 30, 2, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_SexCode="+GAT_SexCode);
                        String ReserveA = (new String(dataBuf, 32, 4, "UTF-16LE")).trim();
                        Log.e(TAG,"ReserveA="+ReserveA);
                        String GAT_Birthday = (new String(dataBuf, 36, 16, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_Birthday="+GAT_Birthday);
                        String GAT_Address = (new String(dataBuf, 52, 70, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_Address="+GAT_Address);
                        String GAT_IDNo = (new String(dataBuf, 122, 36, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_IDNo="+GAT_IDNo);
                        String GAT_IssuingAuthority = (new String(dataBuf, 158, 30, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_IssuingAuthority="+GAT_IssuingAuthority);
                        String GAT_ValidStartDate = (new String(dataBuf, 188, 16, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_ValidStartDate="+GAT_ValidStartDate);
                        String GAT_ValidEndDate = (new String(dataBuf, 204, 16, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_ValidEndDate="+GAT_ValidEndDate);
                        String GAT_PassportNo = (new String(dataBuf, 220, 18, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_PassportNo="+GAT_PassportNo);
                        String GAT_IssuingNo = (new String(dataBuf, 238, 4, "UTF-16LE")).trim();
                        Log.e(TAG,"GAT_IssuingNo="+GAT_IssuingNo);
                        String ReserveB = (new String(dataBuf, 242, 6, "UTF-16LE")).trim();
                        Log.e(TAG,"ReserveB="+ReserveB);
                        String ReserveC = (new String(dataBuf, 250, 6, "UTF-16LE")).trim();
                        Log.e(TAG,"ReserveC="+ReserveC);

                        String Gender;
                        String GAT_Sex;
                        if(GAT_SexCode.equals("1")) {
                            Gender = "男";
                            GAT_Sex = "男";
                        } else {
                            Gender = "女";
                            GAT_Sex = "女";
                        }


                        people.fullName = GAT_Name;
//                bean.icon = decodePhoto(recvBuf);
                        people.birthday = GAT_Birthday;
                        people.idNo = GAT_IDNo;
                        people.idOrg = GAT_IssuingAuthority;
                        people.beginDate = GAT_ValidStartDate;
                        people.endDate = GAT_ValidEndDate;
                        people.idAddr = GAT_Address;
                        people.sex = Gender;
                        people.cardType = "J";
                        people.reserveA = ReserveA;
                        people.reserveB = ReserveB;
                        people.reserveC = ReserveC;
                        people.issuingNo= GAT_IssuingNo;

                        people.passportNo= GAT_PassportNo;


                    }else {
                        decodeInfo[0] = TmpStr.substring(0, 15); //name
                        decodeInfo[1] = TmpStr.substring(15, 16); // gender(1)
                        decodeInfo[2] = TmpStr.substring(16, 18); // nation (2)
                        decodeInfo[3] = TmpStr.substring(18, 26); // birthday (8)
                        decodeInfo[4] = TmpStr.substring(26, 61); // address
                        decodeInfo[5] = TmpStr.substring(61, 79); //id (18)
                        decodeInfo[6] = TmpStr.substring(79, 94); //depart (15)
                        decodeInfo[7] = TmpStr.substring(94, 102); // tsYYMMDD
                        decodeInfo[8] = TmpStr.substring(102, 110); //tpYYMMDD
                        decodeInfo[9] = TmpStr.substring(110, 119);
                        decodeInfo[10] = TmpStr.substring(119, 121);
                        decodeInfo[11] = TmpStr.substring(124, 125);


                        if (decodeInfo[1].equals("1"))
                            decodeInfo[1] = "男";
                        else
                            decodeInfo[1] = "女";

                        String nation = "";
                        if(!decodeInfo[2].equals("  ")) {
                            int code = Integer.parseInt(decodeInfo[2]);
                            LogUtil.e(TAG,"民族code==" + code);
                            nation = decodeNation(code);
                        }

                        // 姓名
                        people.setFullName(decodeInfo[0]);
                        // 性别
                        people.setSex(decodeInfo[1]);
                        // 民族
                        people.setNation(nation);
                        // 出生
                        people.setBirthday(decodeInfo[3]);
                        // 住址
                        people.setIdAddr(decodeInfo[4]);
                        // 身份证号
                        people.setIdNo(decodeInfo[5]);
                        // 签发机关
                        people.setIdOrg(decodeInfo[6]);
                        // 有效起始日期
                        people.setBeginDate(decodeInfo[7]);
                        // 有效截止日期
                        people.setEndDate(decodeInfo[8]);
                        people.setCardType("A");
                        if(finger != null){
//                            people.setFingerByte(finger);
                            people.setFingerStr(ByteTool.byte2hex(finger));
//                            LogUtil.e(TAG,"指纹数据：" +ByteTool.byte2hex(people.getFingerByte())  );
                        }

                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }

        return people;
    }
    public List<String> mList =null ;
    private String decodeNation(int code) {
        init_date();
        String nation;
        if(mList == null) {
            //DisplayError("Not found nation code");
            return "";
        }

        Log.d("idreader","code "+code);

        if(code >= 1 && code <= 56)
        {
            nation = mList.get(code);
        }else if(code == 97) {
            nation = MainActivity.context.getResources().getString(R.string.case_97_nation);
        }else if(code == 98){
            nation = MainActivity.context.getResources().getString(R.string.case_98_nation);
        }else {
            nation = mList.get(0);
            nation=" ";
        }

        Log.d("idreader","nation "+ nation);
        return nation;
    }
    public void init_date(){
        mList= new ArrayList<String>();

        mList.add(0,"");
        mList.add(1, MainActivity.context.getResources().getString(R.string.case_1_nation));
        mList.add(2, MainActivity.context.getResources().getString(R.string.case_2_nation));
        mList.add(3, MainActivity.context.getResources().getString(R.string.case_3_nation));
        mList.add(4, MainActivity.context.getResources().getString(R.string.case_4_nation));
        mList.add(5, MainActivity.context.getResources().getString(R.string.case_5_nation));
        mList.add(6, MainActivity.context.getResources().getString(R.string.case_6_nation));
        mList.add(7, MainActivity.context.getResources().getString(R.string.case_7_nation));
        mList.add(8, MainActivity.context.getResources().getString(R.string.case_8_nation));
        mList.add(9, MainActivity.context.getResources().getString(R.string.case_9_nation));
        mList.add(10, MainActivity.context.getResources().getString(R.string.case_10_nation));
        mList.add(11, MainActivity.context.getResources().getString(R.string.case_11_nation));
        mList.add(12, MainActivity.context.getResources().getString(R.string.case_12_nation));
        mList.add(13, MainActivity.context.getResources().getString(R.string.case_12_nation));
        mList.add(14, MainActivity.context.getResources().getString(R.string.case_14_nation));
        mList.add(15, MainActivity.context.getResources().getString(R.string.case_15_nation));
        mList.add(16, MainActivity.context.getResources().getString(R.string.case_16_nation));
        mList.add(17, MainActivity.context.getResources().getString(R.string.case_17_nation));
        mList.add(18, MainActivity.context.getResources().getString(R.string.case_18_nation));
        mList.add(19, MainActivity.context.getResources().getString(R.string.case_19_nation));
        mList.add(20, MainActivity.context.getResources().getString(R.string.case_20_nation));
        mList.add(21, MainActivity.context.getResources().getString(R.string.case_21_nation));
        mList.add(22, MainActivity.context.getResources().getString(R.string.case_22_nation));
        mList.add(23, MainActivity.context.getResources().getString(R.string.case_23_nation));
        mList.add(24, MainActivity.context.getResources().getString(R.string.case_24_nation));
        mList.add(25, MainActivity.context.getResources().getString(R.string.case_25_nation));
        mList.add(26, MainActivity.context.getResources().getString(R.string.case_26_nation));
        mList.add(27, MainActivity.context.getResources().getString(R.string.case_27_nation));
        mList.add(28, MainActivity.context.getResources().getString(R.string.case_28_nation));
        mList.add(29, MainActivity.context.getResources().getString(R.string.case_29_nation));
        mList.add(30, MainActivity.context.getResources().getString(R.string.case_30_nation));
        mList.add(31, MainActivity.context.getResources().getString(R.string.case_31_nation));
        mList.add(32, MainActivity.context.getResources().getString(R.string.case_32_nation));
        mList.add(33, MainActivity.context.getResources().getString(R.string.case_33_nation));
        mList.add(34, MainActivity.context.getResources().getString(R.string.case_34_nation));
        mList.add(35, MainActivity.context.getResources().getString(R.string.case_35_nation));
        mList.add(36, MainActivity.context.getResources().getString(R.string.case_36_nation));
        mList.add(37, MainActivity.context.getResources().getString(R.string.case_37_nation));
        mList.add(38, MainActivity.context.getResources().getString(R.string.case_38_nation));
        mList.add(39, MainActivity.context.getResources().getString(R.string.case_39_nation));
        mList.add(40, MainActivity.context.getResources().getString(R.string.case_40_nation));
        mList.add(41, MainActivity.context.getResources().getString(R.string.case_41_nation));
        mList.add(42, MainActivity.context.getResources().getString(R.string.case_42_nation));
        mList.add(43, MainActivity.context.getResources().getString(R.string.case_43_nation));
        mList.add(44, MainActivity.context.getResources().getString(R.string.case_44_nation));
        mList.add(45, MainActivity.context.getResources().getString(R.string.case_43_nation));
        mList.add(46, MainActivity.context.getResources().getString(R.string.case_46_nation));
        mList.add(47, MainActivity.context.getResources().getString(R.string.case_47_nation));
        mList.add(48, MainActivity.context.getResources().getString(R.string.case_48_nation));
        mList.add(49, MainActivity.context.getResources().getString(R.string.case_49_nation));
        mList.add(50, MainActivity.context.getResources().getString(R.string.case_50_nation));
        mList.add(51, MainActivity.context.getResources().getString(R.string.case_51_nation));
        mList.add(52, MainActivity.context.getResources().getString(R.string.case_52_nation));
        mList.add(53, MainActivity.context.getResources().getString(R.string.case_53_nation));
        mList.add(54, MainActivity.context.getResources().getString(R.string.case_54_nation));
        mList.add(55, MainActivity.context.getResources().getString(R.string.case_55_nation));
        mList.add(56, MainActivity.context.getResources().getString(R.string.case_56_nation));
    }

    private IdentityInfoBean decodeInfo(byte[] buffer, boolean haveFinger, boolean decodePhoto ,String ceshi) {
        IdentityInfoBean people = new IdentityInfoBean();
        String temp = null;
        int nPtr = 3;
        short textSize = ByteTool.getShort(buffer[nPtr + 0], buffer[nPtr + 1]);
        short imageSize = ByteTool.getShort(buffer[nPtr + 2], buffer[nPtr + 3]);
        short fingerSize = 0;
        if (haveFinger) {
            fingerSize = ByteTool.getShort(buffer[nPtr + 4], buffer[nPtr + 5]);
            nPtr += 6;
        } else nPtr += 4;
        byte[] text = new byte[textSize];
        System.arraycopy(buffer, nPtr, text, 0, textSize);
        byte[] image = new byte[imageSize];
        System.arraycopy(buffer, nPtr + textSize, image, 0, imageSize);
        people.setImageByte(image);
        if (decodePhoto) {

            people.setIcon(WltLib.parsePhotoOther(image));

        }
        try {
            String cardType = new String(text, 248, 2, "UTF-16LE").trim();//证件类型
            Log.e("cardType", cardType);

            if (cardType.equals("I")) {

                String enName = new String(text, 0, 120, "UTF-16LE").trim();

                Log.e("enName", enName);
                people.setEnName(enName);

                String fprSex = new String(text, 120, 2, "UTF-16LE").trim();

                if (fprSex.equals("1"))
                    fprSex = "男";
                else
                    fprSex = "女";
                people.setSex(fprSex);

                String frpIDNo = new String(text, 122, 30, "UTF-16LE").trim();

                Log.e("frpIDNo", frpIDNo);

                people.setIdNo(frpIDNo);

                String countryCode = new String(text, 152, 6, "UTF-16LE").trim();

                people.setCountryCode(countryCode);

                Log.e("countryCode", countryCode);

                String CHNName = new String(text, 158, 30, "UTF-16LE").trim();

                Log.e("CHNName", CHNName);

                people.setFullName(CHNName);

                String validStart = new String(text, 188, 16, "UTF-16LE").trim();

                Log.e("validStart", validStart);

                people.setBeginDate(validStart);

                String validEnd = new String(text, 204, 16, "UTF-16LE").trim();

                Log.e("validEnd", validEnd);

                people.setEndDate(validEnd);

                String Birthday = new String(text, 220, 16, "UTF-16LE").trim();

                Log.e("Birthday", Birthday);

                people.setBirthday(Birthday);

                String idVer = new String(text, 236, 4, "UTF-16LE").trim();

                Log.e("idVer", idVer);

                people.setCardVer(idVer);

                String issuingAuthorityCode = new String(text, 240, 8, "UTF-16LE").trim();

                Log.e("issuingAuthorityCode", issuingAuthorityCode);

                people.setIdOrg(issuingAuthorityCode);

                people.setCardType("I");

                people.setNation(countryMap.get(countryCode));


            } else {

                byte[] finger = null;
                if (fingerSize > 0) {
                    finger = new byte[fingerSize];
                    System.arraycopy(buffer, nPtr + textSize + imageSize, finger, 0, fingerSize);
                    people.setFingerByte(finger);
                }

                // 姓名
                temp = new String(text, 0, 30, "UTF-16LE").trim();
                people.setFullName(temp);
                // 性别
                temp = new String(text, 30, 2, "UTF-16LE");
                if (temp.equals("1"))
                    temp = "男";
                else
                    temp = "女";
                people.setSex(temp);
                // 民族
                temp = new String(text, 32, 4, "UTF-16LE");
                try {
                    int code = Integer.parseInt(temp.toString());
                    temp = parseNation(code);
                } catch (Exception e) {
                    temp = "";
                }
                people.setNation(temp);
                // 出生
                temp = new String(text, 36, 16, "UTF-16LE").trim();
                people.setBirthday(temp);
                // 住址
                temp = new String(text, 52, 70, "UTF-16LE").trim();
                people.setIdAddr(temp);
                // 身份证号
                temp = new String(text, 122, 36, "UTF-16LE").trim();
                people.setIdNo(temp);
                // 签发机关
                temp = new String(text, 158, 30, "UTF-16LE").trim();
                people.setIdOrg(temp);
                // 有效起始日期
                temp = new String(text, 188, 16, "UTF-16LE").trim();
                people.setBeginDate(temp);
                // 有效截止日期
                temp = new String(text, 204, 16, "UTF-16LE").trim();
                people.setEndDate(temp);
                people.setCardType(cardType);
            }

        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            return null;
        }
        return people;
    }

    public byte[] ReadSAMIDBuf(String[] sRet) {
        Log.i(TAG, "ReadSAMIDBuf()");
        byte[] mBuffer = new byte[2320];
        int[] length = new int[1];
        boolean bRet = SendAndRecv(sCmdReadSAMID, mBuffer, length, 3000);
        if (!bRet) {
            Log.e(TAG, "ReadSAMIDBuf() SendAndRecv() error!");
            return null;
        }
        if (mBuffer[0] == (byte) 0x00 && mBuffer[1] == (byte) 0x00 && mBuffer[2] == (byte) 0x90) {
            byte[] tmp = new byte[16];
            System.arraycopy(mBuffer, 3, tmp, 0, tmp.length);
            Log.d(TAG, "ReadSAMIDBuf() tmp = " + tmp);
            return tmp;
        }
        Log.e(TAG, "ReadSAMIDBuf() error!");
        return null;
    }

    public String ReadSAMID(byte[] mBuffer, String[] sRet) {
        String sSAMID = "";
        boolean isTryOpen = false;
        try {
            if (!isOpen) {
                return null;
            }
            int[] length = new int[1];
            boolean bRet = SendAndRecv(sCmdReadSAMID, mBuffer, length, 1000);
            if (!bRet) return sSAMID;
            if (mBuffer[0] == (byte) 0x00 && mBuffer[1] == (byte) 0x00 && mBuffer[2] == (byte) 0x90) {
                String temp1 = ByteTool.byteToHexString(mBuffer[3]);
                String temp2 = ByteTool.byteToHexString(mBuffer[5]);
                byte[] temp3 = new byte[4];
                System.arraycopy(mBuffer, 7, temp3, 0, temp3.length);
                ByteTool.reversal(temp3);
                byte[] temp4 = new byte[4];
                System.arraycopy(mBuffer, 11, temp4, 0, temp4.length);
                ByteTool.reversal(temp4);
                byte[] temp5 = new byte[4];
                System.arraycopy(mBuffer, 15, temp5, 0, temp5.length);
                ByteTool.reversal(temp5);
                StringBuffer sb = new StringBuffer();
                sb.append(temp1);
                sb.append(".");
                sb.append(temp2);
                sb.append("-");
                sb.append(ByteTool.byteArray2int(temp3));
                sb.append("-");
                String str4 = Long.toString(ByteTool.byteArray2int(temp4));
                for (int i = 0; i < 10 - str4.length(); i++) {
                    sb.append("0");
                }
                sb.append(str4);
                sb.append("-");
                String str5 = Long.toString(ByteTool.byteArray2int(temp5));
                for (int i = 0; i < 10 - str5.length(); i++) {
                    sb.append("0");
                }
                sb.append(str5);
                sSAMID = sb.toString();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } finally {
            if (isTryOpen) {
                isOpen = false;
                closeSerialPort();
            }
        }
        return sSAMID;
    }

    private boolean SendAndRecv(String sSendCmd, byte[] mBuffer, int[] length, int nWaitTime) {
        int nLen = 0;
        if (!isOpen) return false;

        try {
            byte[] cmd = ByteTool.hexStr2Bytes(sSendCmd);
            writeFlush(cmd, cmd.length);
            Log.e("send:", sSendCmd);
            int nRet = receiveBytes(mBuffer, 7, nWaitTime);
            if (nRet != 7) {
                Log.e("read err1", "==" +ByteTool.byte2hex(mBuffer, 0, nRet, false));
                return false;
            }
            if (mBuffer[0] == (byte) 0xaa && mBuffer[1] == (byte) 0xaa && mBuffer[2] == (byte) 0xaa && mBuffer[3] == (byte) 0x96 && mBuffer[4] == (byte) 0x69) {
                nLen = ByteTool.getShort(mBuffer[5], mBuffer[6]);
                nRet = receiveBytes(mBuffer, nLen, nWaitTime);
                if (nRet != nLen) {
                    Log.e("read err2", "==" + String.valueOf(nRet));
                    return false;
                }
                length[0] = nLen + 7;
                Log.e("rev2", ByteTool.byte2hex(mBuffer, 0, nLen, false));
                return true;
            } else {
                Log.e("read err2:", ByteTool.byte2hex(mBuffer, 0, 7, false));
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return false;
    }


    public void PowerOnReader() {

        // rkGpioControlNative.ControlGpio(rkGpioControlNative.RK30_PIN0_PC6, 1);

    }

    public void PowerOffReader() {

        // rkGpioControlNative.ControlGpio(rkGpioControlNative.RK30_PIN0_PC6, 0);

    }

    public void ReleaseReader() {
        Log.d(TAG, "ReleaseReader()");
        isOpen = false;
        closeSerialPort();
        // ourInstance = null;

    }

    protected String parseNation(int code) {
        String nation;
        switch (code) {
            case 1:
                nation = "汉";
                break;
            case 2:
                nation = "蒙古";
                break;
            case 3:
                nation = "回";
                break;
            case 4:
                nation = "藏";
                break;
            case 5:
                nation = "维吾尔";
                break;
            case 6:
                nation = "苗";
                break;
            case 7:
                nation = "彝";
                break;
            case 8:
                nation = "壮";
                break;
            case 9:
                nation = "布依";
                break;
            case 10:
                nation = "朝鲜";
                break;
            case 11:
                nation = "满";
                break;
            case 12:
                nation = "侗";
                break;
            case 13:
                nation = "瑶";
                break;
            case 14:
                nation = "白";
                break;
            case 15:
                nation = "土家";
                break;
            case 16:
                nation = "哈尼";
                break;
            case 17:
                nation = "哈萨克";
                break;
            case 18:
                nation = "傣";
                break;
            case 19:
                nation = "黎";
                break;
            case 20:
                nation = "傈僳";
                break;
            case 21:
                nation = "佤";
                break;
            case 22:
                nation = "畲";
                break;
            case 23:
                nation = "高山";
                break;
            case 24:
                nation = "拉祜";
                break;
            case 25:
                nation = "水";
                break;
            case 26:
                nation = "东乡";
                break;
            case 27:
                nation = "纳西";
                break;
            case 28:
                nation = "景颇";
                break;
            case 29:
                nation = "柯尔克孜";
                break;
            case 30:
                nation = "土";
                break;
            case 31:
                nation = "达斡尔";
                break;
            case 32:
                nation = "仫佬";
                break;
            case 33:
                nation = "羌";
                break;
            case 34:
                nation = "布朗";
                break;
            case 35:
                nation = "撒拉";
                break;
            case 36:
                nation = "毛南";
                break;
            case 37:
                nation = "仡佬";
                break;
            case 38:
                nation = "锡伯";
                break;
            case 39:
                nation = "阿昌";
                break;
            case 40:
                nation = "普米";
                break;
            case 41:
                nation = "塔吉克";
                break;
            case 42:
                nation = "怒";
                break;
            case 43:
                nation = "乌孜别克";
                break;
            case 44:
                nation = "俄罗斯";
                break;
            case 45:
                nation = "鄂温克";
                break;
            case 46:
                nation = "德昂";
                break;
            case 47:
                nation = "保安";
                break;
            case 48:
                nation = "裕固";
                break;
            case 49:
                nation = "京";
                break;
            case 50:
                nation = "塔塔尔";
                break;
            case 51:
                nation = "独龙";
                break;
            case 52:
                nation = "鄂伦春";
                break;
            case 53:
                nation = "赫哲";
                break;
            case 54:
                nation = "门巴";
                break;
            case 55:
                nation = "珞巴";
                break;
            case 56:
                nation = "基诺";
                break;
            case 57:
                nation = "穿青人";
                break;
            case 97:
                nation = "其他";
                break;
            case 98:
                nation = "外国血统中国籍人士";
                break;
            default:
                nation = "";
        }
        return nation;
    }

    final static HashMap<String, String> countryMap = new HashMap<String, String>();

    static {
        countryMap.put("AFG", "阿富汗");
        countryMap.put("ALB", "阿尔巴尼亚");
        countryMap.put("DZA", "阿尔及利亚");
        countryMap.put("ASM", "美属萨摩亚");
        countryMap.put("AND", "安道尔");
        countryMap.put("AGO", "安哥拉");
        countryMap.put("AIA", "安圭拉");
        countryMap.put("ATA", "南极洲");
        countryMap.put("ATG", "安提瓜和巴布达");
        countryMap.put("ARG", "阿根廷");
        countryMap.put("ARM", "亚美尼亚");
        countryMap.put("ABW", "阿鲁巴");
        countryMap.put("AUS", "澳大利亚");
        countryMap.put("AUT", "奥地利");
        countryMap.put("AZE", "阿塞拜疆");
        countryMap.put("BHS", "巴哈马");
        countryMap.put("BHR", "巴林");
        countryMap.put("BGD", "孟加拉国");
        countryMap.put("BRB", "巴巴多斯");
        countryMap.put("BLR", "白俄罗斯");
        countryMap.put("BEL", "比利时");
        countryMap.put("BLZ", "伯利兹");
        countryMap.put("BEN", "贝宁");
        countryMap.put("BMU", "百慕大");
        countryMap.put("BTN", "不丹");
        countryMap.put("BOL", "玻利维亚");
        countryMap.put("BIH", "波黑");
        countryMap.put("BWA", "博茨瓦纳");
        countryMap.put("BVT", "布维岛");
        countryMap.put("BRA", "巴西");
        countryMap.put("IOT", "英属印度洋领土");
        countryMap.put("BRN", "文莱");
        countryMap.put("BGR", "保加利亚");
        countryMap.put("BFA", "布基纳法索");
        countryMap.put("BDI", "布隆迪");
        countryMap.put("KHM", "柬埔寨");
        countryMap.put("CMR", "喀麦隆");
        countryMap.put("CAN", "加拿大");
        countryMap.put("CPV", "佛得角");
        countryMap.put("CYM", "开曼群岛");
        countryMap.put("CAF", "中非");
        countryMap.put("TCD", "乍得");
        countryMap.put("CHL", "智利");
        countryMap.put("CHN", "中国");
        countryMap.put("HKG", "香港");
        countryMap.put("MAC", "澳门");
        countryMap.put("TWN", "台湾");
        countryMap.put("CSR", "圣诞岛");
        countryMap.put("CCK", "科科斯(基林)群岛");
        countryMap.put("COL", "哥伦比亚");
        countryMap.put("COM", "科摩罗");
        countryMap.put("COG", "刚果（布）");
        countryMap.put("COD", "刚果（金）");
        countryMap.put("COK", "库克群岛");
        countryMap.put("CR", "哥斯达黎加");
        countryMap.put("CIV", "科特迪瓦");
        countryMap.put("HRV", "克罗地亚");
        countryMap.put("CUB", "古巴");
        countryMap.put("CYP", "塞浦路斯");
        countryMap.put("CZE", "捷克");
        countryMap.put("DNK", "丹麦");
        countryMap.put("DJI", "吉布提");
        countryMap.put("DMA", "多米尼克");
        countryMap.put("DOM", "多米尼加共和国");
        countryMap.put("TMP", "东帝汶");
        countryMap.put("ECU", "厄瓜多尔");
        countryMap.put("EGY", "埃及");
        countryMap.put("SLV", "萨尔瓦多");
        countryMap.put("GNQ", "赤道几内亚");
        countryMap.put("ERI", "厄立特里亚");
        countryMap.put("EST", "爱沙尼亚");
        countryMap.put("ETH", "埃塞俄比亚");
        countryMap.put("FLK", "福克兰群岛(马尔维纳斯)");
        countryMap.put("FRO", "法罗群岛");
        countryMap.put("FJI", "斐济");
        countryMap.put("FIN", "芬兰");
        countryMap.put("FRA", "法国");
        countryMap.put("GUF", "法属圭亚那");
        countryMap.put("PYF", "法属波利尼西亚");
        countryMap.put("ATF", "法属南部领土");
        countryMap.put("GAB", "加蓬");
        countryMap.put("GMB", "冈比亚Gambia");
        countryMap.put("GEO", "格鲁吉亚");
        countryMap.put("DEU", "德国");
        countryMap.put("GHA", "加纳");
        countryMap.put("GIB", "直布罗陀");
        countryMap.put("GRC", "希腊");
        countryMap.put("GRL", "格陵兰");
        countryMap.put("GRD", "格林纳达");
        countryMap.put("GLP", "瓜德罗普");
        countryMap.put("GUM", "关岛");
        countryMap.put("GTM", "危地马拉");
        countryMap.put("GIN", "几内亚");
        countryMap.put("GNB", "几内亚比绍");
        countryMap.put("GUY", "圭亚那");
        countryMap.put("HTI", "海地");
        countryMap.put("HMD", "赫德岛和麦克唐纳岛");
        countryMap.put("HND", "洪都拉斯");
        countryMap.put("HUN", "匈牙利");
        countryMap.put("ISL", "冰岛");
        countryMap.put("IND", "印度");
        countryMap.put("IDN", "印度尼西亚");
        countryMap.put("IRN", "伊朗");
        countryMap.put("IRQ", "伊拉克");
        countryMap.put("IRL", "爱尔兰");
        countryMap.put("ISR", "以色列");
        countryMap.put("ITA", "意大利");
        countryMap.put("JAM", "牙买加");
        countryMap.put("JPN", "日本");
        countryMap.put("JOR", "约旦");
        countryMap.put("KAZ", "哈萨克斯坦");
        countryMap.put("KEN", "肯尼亚");
        countryMap.put("KIR", "基里巴斯");
        countryMap.put("PRK", "朝鲜");
        countryMap.put("KOR", "韩国");
        countryMap.put("KWT", "科威特");
        countryMap.put("KGZ", "吉尔吉斯斯坦");
        countryMap.put("LAO", "老挝");
        countryMap.put("LVA", "拉脱维亚");
        countryMap.put("LBN", "黎巴嫩");
        countryMap.put("LSO", "莱索托");
        countryMap.put("LBR", "利比里亚");
        countryMap.put("LBY", "利比亚");
        countryMap.put("LIE", "列支敦士登");
        countryMap.put("LTU", "立陶宛");
        countryMap.put("LUX", "卢森堡");
        countryMap.put("MKD", "前南马其顿");
        countryMap.put("MDG", "马达加斯加");
        countryMap.put("MWI", "马拉维");
        countryMap.put("MYS", "马来西亚");
        countryMap.put("MDV", "马尔代夫");
        countryMap.put("MLI", "马里");
        countryMap.put("MLT", "马耳他");
        countryMap.put("MHL", "马绍尔群岛");
        countryMap.put("MTQ", "马提尼克");
        countryMap.put("MRT", "毛里塔尼亚");
        countryMap.put("MUS", "毛里求斯");
        countryMap.put("MYT", "马约特");
        countryMap.put("MEX", "墨西哥");
        countryMap.put("FSM", "密克罗尼西亚联邦");
        countryMap.put("MDA", "摩尔多瓦");
        countryMap.put("MCO", "摩纳哥");
        countryMap.put("MNG", "蒙古");
        countryMap.put("MSR", "蒙特塞拉特");
        countryMap.put("MAR", "摩洛哥");
        countryMap.put("MOZ", "莫桑比克");
        countryMap.put("MMR", "缅甸");
        countryMap.put("NAM", "纳米比亚");
        countryMap.put("NRU", "瑙鲁");
        countryMap.put("NPL", "尼泊尔");
        countryMap.put("NLD", "荷兰");
        countryMap.put("ANT", "荷属安的列斯");
        countryMap.put("NCL", "新喀里多尼亚");
        countryMap.put("NZL", "新西兰");
        countryMap.put("NIC", "尼加拉瓜");
        countryMap.put("NER", "尼日尔");
        countryMap.put("NGA", "尼日利亚");
        countryMap.put("NIU", "纽埃");
        countryMap.put("NFK", "诺福克岛");
        countryMap.put("MNP", "北马里亚纳");
        countryMap.put("NOR", "挪威");
        countryMap.put("OMN", "阿曼");
        countryMap.put("PAK", "巴基斯坦");
        countryMap.put("PLW", "帕劳");
        countryMap.put("PST", "巴勒斯坦");
        countryMap.put("PAN", "巴拿马");
        countryMap.put("PNG", "巴布亚新几内亚");
        countryMap.put("PRY", "巴拉圭");
        countryMap.put("PER", "秘鲁");
        countryMap.put("PHL", "菲律宾");
        countryMap.put("PCN", "皮特凯恩群岛");
        countryMap.put("POL", "波兰");
        countryMap.put("PRT", "葡萄牙");
        countryMap.put("PRI", "波多黎各");
        countryMap.put("QAT", "卡塔尔");
        countryMap.put("REU", "留尼汪");
        countryMap.put("ROM", "罗马尼亚");
        countryMap.put("RUS", "俄罗斯联邦");
        countryMap.put("RWA", "卢旺达");
        countryMap.put("SHN", "圣赫勒拿");
        countryMap.put("KNA", "圣基茨和尼维斯");
        countryMap.put("LCA", "圣卢西亚");
        countryMap.put("SPM", "圣皮埃尔和密克隆");
        countryMap.put("VCT", "圣文森特和格林纳丁斯");
        countryMap.put("WSM", "萨摩亚");
        countryMap.put("SMR", "圣马力诺");
        countryMap.put("STp", "圣多美和普林西比");
        countryMap.put("SAU", "沙特阿拉伯");
        countryMap.put("SEN", "塞内加尔");
        countryMap.put("SYC", "塞舌尔");
        countryMap.put("SLE", "塞拉利昂");
        countryMap.put("SGP", "新加坡");
        countryMap.put("SVK", "斯洛伐克");
        countryMap.put("SVN", "斯洛文尼亚");
        countryMap.put("SLB", "所罗门群岛");
        countryMap.put("SOM", "索马里");
        countryMap.put("ZAF", "南非");
        countryMap.put("SGS", "南乔治亚岛和南桑德韦奇岛");
        countryMap.put("ESP", "西班牙");
        countryMap.put("LKA", "斯里兰卡");
        countryMap.put("SDN", "苏丹");
        countryMap.put("SUR", "苏里南");
        countryMap.put("SJM", "斯瓦尔巴群岛");
        countryMap.put("SWZ", "斯威士兰");
        countryMap.put("SWE", "瑞典");
        countryMap.put("CHE", "瑞士");
        countryMap.put("SYR", "叙利亚");
        countryMap.put("TJK", "塔吉克斯坦");
        countryMap.put("TZA", "坦桑尼亚");
        countryMap.put("THA", "泰国");
        countryMap.put("TGO", "多哥");
        countryMap.put("TKL", "托克劳");
        countryMap.put("TON", "汤加");
        countryMap.put("TTO", "特立尼达和多巴哥");
        countryMap.put("TUN", "突尼斯");
        countryMap.put("TUR", "土耳其");
        countryMap.put("TKM", "土库曼斯坦");
        countryMap.put("TCA", "特克斯科斯群岛");
        countryMap.put("TUV", "图瓦卢");
        countryMap.put("UGA", "乌干达");
        countryMap.put("UKR", "乌克兰");
        countryMap.put("ARE", "阿联酋");
        countryMap.put("GBR", "英国");
        countryMap.put("USA", "美国");
        countryMap.put("UMI", "美国本土外小岛屿");
        countryMap.put("URY", "乌拉圭");
        countryMap.put("UZB", "乌兹别克斯坦");
        countryMap.put("VUT", "瓦努阿图");
        countryMap.put("VAT", "梵蒂冈");
        countryMap.put("VEN", "委内瑞拉");
        countryMap.put("VNM", "越南");
        countryMap.put("VGB", "英属维尔京群岛");
        countryMap.put("VIR", "美属维尔京群岛");
        countryMap.put("WLF", "瓦利斯和富图纳");
        countryMap.put("ESH", "西撒哈拉");
        countryMap.put("YEM", "也门");
        countryMap.put("YUG", "南斯拉夫");
        countryMap.put("ZMB", "赞比亚");
        countryMap.put("ZWE", "津巴布韦");
    }


//    public void lightOn() {
//
//        int gpio = rkGpioControlNative.ControlGpio(rkGpioControlNative.ID_LIGHT, 1);
//        Log.e("gpioID", gpio + "--");
//    }
//
//    public void lightOff() {
//
//        int gpio = rkGpioControlNative.ControlGpio(rkGpioControlNative.ID_LIGHT, 0);
//        Log.e("gpioID", gpio + "--");
//    }
}
